import api from '@/common/utils/api' //接口
import { generateUUID } from '@/common/utils/index'
import NodeRSA from 'node-rsa'

export function generateKeyPair(pkcsType, pkcsSize) {
  pkcsType = pkcsType || 'pkcs8' // 不为空则 设置为传入参数，为空则 设置为 pkcs8
  pkcsSize = pkcsSize || 1024
  // 1.创建RSA对象，并指定 秘钥长度
  let key = new NodeRSA({
    b: pkcsSize,
  })
  key.setOptions({
    encryptionScheme: 'pkcs1',
  }) // 指定加密格式
  // 2.生成 公钥私钥，使用 pkcs8标准，pem格式
  let publicPem = key.exportKey(pkcsType + '-public-hex') // 制定输出格式
  let privatePem = key.exportKey(pkcsType + '-private-hex')
  let publicKey = JSON.stringify(publicPem)
  let privateKey = JSON.stringify(privatePem)
  publicKey = publicKey
    .substring(publicKey.indexOf('\\n') + 2, publicKey.lastIndexOf('\\n'))
    .replace(/\\n/g, '') //格式转换 与后台协调
  privateKey = privateKey
    .substring(privateKey.indexOf('\\n') + 2, privateKey.lastIndexOf('\\n'))
    .replace(/\\n/g, '')
  let UUID = generateUUID()
  uni.setStorageSync('deviceId', UUID)
  uni.setStorageSync('privateKey', privateKey)
  uni.setStorageSync('publicKey', publicKey)
  getKey(publicKey, key, UUID)
}

function getKey(publicKey, key, UUID) {
  let par = {
    pubKey: publicKey,
    deviceCode: UUID,
  }
  api.postPublicKey(par).then((res) => {
    decryptKey(res.data.key, key)
  })
}

function decryptKey(encryData, key) {
  var decryptData = key.decrypt(encryData, 'utf8')
  uni.setStorageSync('Key', decryptData)
}
